package com.evendai.sipdemo

import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.view.View
import com.evendai.loglibrary.Timber
import com.evendai.sipdemo.databinding.ActivityLoginBinding
import com.evendai.sipdemo.sip.helper.SipRegisterHelper
import com.evendai.sipdemo.util.Utils
import org.jetbrains.anko.startActivity

class LoginActivity : BaseActivity() {

    val binding: ActivityLoginBinding by lazy { ActivityLoginBinding.inflate(layoutInflater, getContentContainer(), true) }

    private val requestFloatWindowPermissionCode = 100

    override fun initView() {
        Utils.initLoginActivityViews(this)
        setLoadingText("正在注册...")
    }

    override fun initListener() {
        Utils.setLoginActivityEditTextInputListener(this)
        binding.btnRegister.setOnClickListener(::register)
    }

    override fun initData() {
        Utils.requestFloatViewPermission(this, requestFloatWindowPermissionCode)
    }

    private fun register(@Suppress("UNUSED_PARAMETER") v: View) {
        if (!Utils.hasActiveNetwork()) {
            showOneButtonDialog("没有可用网络")
            return
        }

        showLoading()

        SipRegisterHelper.register() { registerSuccess, failDesc ->
            if (registerSuccess) {
                startActivity<MainActivity>()
                PersistentVariables.isLogout = false
            } else {
                showOneButtonDialog("sip注册失败：$failDesc")
                PersistentVariables.isLogout = true
            }
            hideLoading()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 获取悬浮窗权限请求结果
        if (requestCode == requestFloatWindowPermissionCode
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            if (Settings.canDrawOverlays(this)) {
                Timber.i("用户给予悬浮窗权限了")
            } else {
                Timber.i("用户没给悬浮窗权限")
                Utils.requestFloatViewPermission(this, requestFloatWindowPermissionCode)
            }
        }
    }


}